package com.binest.meetingInclusion.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.query_dsl.*;


import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.search.Hit;

import com.binest.common.constant.HttpStatus;
import com.binest.common.core.domain.entity.SysUser;
import com.binest.common.core.domain.model.LoginUser;
import com.binest.common.core.page.TableDataInfo;
import com.binest.common.utils.DateUtils;
import com.binest.common.utils.uuid.IdUtils;
import com.binest.draftBox.domain.DraftBox;
import com.binest.draftBox.mapper.DraftBoxMapper;
import com.binest.inclusionExamine.domain.InclusionExamine;
import com.binest.inclusionExamine.mapper.InclusionExamineMapper;
import com.binest.inclusionExamine.service.IInclusionExamineService;
import com.binest.kolInclusion.domain.KolInclusion;
import com.binest.meetingInclusion.domain.MeetingInclusionVo;
import com.binest.meetingInclusionMain.domain.MeetingInclusionMain;
import com.binest.meetingInclusionMain.mapper.MeetingInclusionMainMapper;

import com.binest.workExperience.domain.WorkExperience;
import com.binest.workExperience.service.IWorkExperienceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.binest.meetingInclusion.mapper.MeetingInclusionMapper;
import com.binest.meetingInclusion.domain.MeetingInclusion;
import com.binest.meetingInclusion.service.IMeetingInclusionService;

import static com.binest.common.utils.SecurityUtils.getLoginUser;


/**
 * 会议收录Service业务层处理
 *
 * @author wwd
 * @date 2024-01-03
 */
@Service
public class MeetingInclusionServiceImpl implements IMeetingInclusionService {
    @Autowired
    private MeetingInclusionMapper meetingInclusionMapper;

    @Autowired
    private IInclusionExamineService inclusionExamineService;
    @Autowired
    private MeetingInclusionMainMapper meetingInclusionMainMapper;


    @Autowired
    private DraftBoxMapper draftBoxMapper;

    @Autowired
    private InclusionExamineMapper inclusionExamineMapper;

    @Autowired
    private  ElasticsearchClient client;
    @Autowired
    private IWorkExperienceService workExperienceService;

    /**
     * 查询会议收录
     *
     * @param id 会议收录主键
     * @return 会议收录
     */
    @Override
    public MeetingInclusion selectMeetingInclusionById(String id)   {
        MeetingInclusion res= meetingInclusionMapper.selectMeetingInclusionById(id);
        InclusionExamine   inclusionExamine=  inclusionExamineMapper.selectInclusionExamineByProjectId(id);
        res.setExamineReport(inclusionExamine.getExamineReport());
        res.setClaimStatus(inclusionExamine.getClaimStatus());
        List<WorkExperience> workExperienceList =workExperienceService.selectWorkExperienceByInId(id);
        if(workExperienceList!=null)
        {
            res.setWorkExperienceList(workExperienceList);
        }
        return res;
    }

    @Override
    public MeetingInclusion selectEsMeetingInclusionById(String id) throws Exception {

        MeetingInclusion res =new MeetingInclusion();
        try {
            // 执行查询
            SearchResponse<MeetingInclusion> searchResponse = client.search(srBuilder -> srBuilder
                            .index("meeting_inclusion")
                            // 多个id查询
                            .query(queryBuilder -> queryBuilder
                                    .ids(idsQueryBuilder -> idsQueryBuilder
                                            .values(id))
                            )
                    , MeetingInclusion.class);

            //解析查询结果

            List<Hit<MeetingInclusion>> hitList = searchResponse.hits().hits();

            res = hitList.get(0).source();

        } catch (IOException e) {
            throw new Exception("查询ES数据失败");

        }


        return res;
    }

    /**
     * 查询会议收录列表
     *
     * @param meetingInclusion 会议收录
     * @return 会议收录
     */
    @Override
    public List<MeetingInclusion> selectMeetingInclusionList(MeetingInclusion meetingInclusion) {

        List<MeetingInclusion> resList=meetingInclusionMapper.selectMeetingInclusionList(meetingInclusion);
        for(MeetingInclusion p:resList){
            String   exStatus= inclusionExamineService.getExamineStatus(p.getId());
            if(exStatus!=null){
                p.setExStatus(exStatus);
            }else{
                p.setExStatus("");
            }
        }
        return resList;

    }

    /**
     * 会议收录 es查询  中英文判断
     * @param meetingInclusion
     * @return
     * @throws Exception
     */
    @Override
    public TableDataInfo selectMeetingInclusionEsList(MeetingInclusionVo meetingInclusion) throws Exception {
        TableDataInfo rspData = new TableDataInfo();
        // 将多个查询条件放入list中.
        List<Query> queries = new ArrayList<>();
        List<Query> querie = new ArrayList<>();

         //最新 最热
         String type="";
         if(meetingInclusion.getType().equals("0")){
             //最新
             type="startTime.keyword";
         }else
         {
             type="likeCount.keyword";
         }
         // 升序降序
        String esSort="";

        if(meetingInclusion.getSort().equals("0")){
            //最新
            esSort="Desc";
        }else
        {
            esSort="Asc";
        }

        //判断中英文  0英文  1中文
            Query byLang=MatchQuery.of(a-> a
                    .field("lang")
                    .query(meetingInclusion.getLang())
            )._toQuery();

            querie.add(byLang);

        //查询条件  关键词模糊查询
        if(meetingInclusion.getTheme()!=null){

            Query byName = WildcardQuery.of(m -> m
                    .field("theme")
                    .value("*"+meetingInclusion.getTheme()+"*")

            )._toQuery();

            Query byContent = WildcardQuery.of(m -> m
                    .field("content")
                    .value("*"+meetingInclusion.getTheme()+"*")

            )._toQuery();



            queries.add(byName);
            queries.add(byContent);
        }
        try {
            // 从es中根据条件查询结果.
            String finalType = type;
            String finalEsSort = esSort;
            SearchResponse<MeetingInclusion> searchResponse = client.search(s -> s
                            .index("meeting_inclusion")
                            .query(q -> q
                                    .bool(t -> t
                                            .should(queries)
                                            .must(querie)

                                    ))
                            .from((meetingInclusion.getPageNum()-1)*meetingInclusion.getPageSize())
                            .size(meetingInclusion.getPageSize())
                            .sort(sort -> sort.field(f -> f.field(finalType).order(SortOrder.valueOf(finalEsSort))))
                    , MeetingInclusion.class);
            List<Hit<MeetingInclusion>> hitList = searchResponse.hits().hits();

            List<MeetingInclusion> list = new ArrayList<>();
            for (Hit<MeetingInclusion> mapHit : hitList) {
                list.add(mapHit.source());
            }

            long total = searchResponse.hits().total() != null ? searchResponse.hits().total().value() : 0;

            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setMsg("查询成功");
            rspData.setRows(list);
            rspData.setTotal(total);

            return rspData;
        }catch (Exception e) {
            throw new Exception("【查询 -> 失败】从es中组合查询出错，错误信息为：{}");
        }

    }


    /**
     * 新增会议收录
     *
     * @param meetingInclusion 会议收录
     * @return 结果
     */
    @Override
    public String insertMeetingInclusion(MeetingInclusion meetingInclusion) {
        //判断存草稿箱还是提交收录
        //存草稿箱
        LoginUser loginUser = getLoginUser();
        SysUser currentUser = loginUser.getUser();

        //判断是否有主表id
        if (meetingInclusion.getMainId() == null) {


            String uuid = IdUtils.simpleUUID();
            String mainId = IdUtils.simpleUUID();
            meetingInclusion.setId(uuid);
            meetingInclusion.setMainId(mainId);
            meetingInclusion.setCreateTime(DateUtils.getNowDate());
            meetingInclusion.setCreateBy(currentUser.getUserId().toString());
            //新增会议收录
            meetingInclusionMapper.insertMeetingInclusion(meetingInclusion);
            //新增会议收录主表
            MeetingInclusionMain meetingInclusionMain = new MeetingInclusionMain();
            meetingInclusionMain.setId(mainId);
            meetingInclusionMain.setCreateTime(DateUtils.getNowDate());
            meetingInclusionMain.setCreateBy(currentUser.getUserId().toString());
            meetingInclusionMainMapper.insertMeetingInclusionMain(meetingInclusionMain);


            if (meetingInclusion.getSubmitType().equals("0")) {

                DraftBox draftBox = new DraftBox();
                draftBox.setId(IdUtils.simpleUUID());
                //会议主题
                draftBox.setName(meetingInclusion.getTheme());
                //类型  会议
                draftBox.setType("3");
                draftBox.setProjectId(uuid);
                draftBox.setUserId(currentUser.getUserId().toString());
                draftBox.setCreateBy(currentUser.getUserId().toString());
                draftBox.setCreateTime(DateUtils.getNowDate());
                draftBoxMapper.insertDraftBox(draftBox);
            } else {

                InclusionExamine inclusionExamine = new InclusionExamine();

                inclusionExamine.setId(IdUtils.simpleUUID());
                //未审核
                inclusionExamine.setStatus("0");
                inclusionExamine.setName(meetingInclusion.getTheme());
                //类型 会议
                inclusionExamine.setType("3");
                inclusionExamine.setProjectId(uuid);
                inclusionExamine.setUserId(currentUser.getUserId().toString());
                inclusionExamine.setCreateBy(currentUser.getUserId().toString());
                inclusionExamine.setCreateTime(DateUtils.getNowDate());
                inclusionExamineMapper.insertInclusionExamine(inclusionExamine);


            }


        } else {
            String uuid = IdUtils.simpleUUID();
            meetingInclusion.setId(uuid);
            meetingInclusion.setCreateTime(DateUtils.getNowDate());
            meetingInclusion.setCreateBy(currentUser.getUserId().toString());

            //新增会议收录
            meetingInclusionMapper.insertMeetingInclusion(meetingInclusion);


            if (meetingInclusion.getSubmitType().equals("0")) {

                DraftBox draftBox = new DraftBox();
                draftBox.setId(IdUtils.simpleUUID());
                //会议主题
                draftBox.setName(meetingInclusion.getTheme());
                //类型  会议
                draftBox.setType("3");
                draftBox.setProjectId(uuid);
                draftBox.setUserId(currentUser.getUserId().toString());
                draftBox.setCreateBy(currentUser.getUserId().toString());
                draftBox.setCreateTime(DateUtils.getNowDate());
                draftBoxMapper.insertDraftBox(draftBox);
            } else {

                InclusionExamine inclusionExamine = new InclusionExamine();

                inclusionExamine.setId(IdUtils.simpleUUID());
                //未审核
                inclusionExamine.setStatus("0");
                inclusionExamine.setName(meetingInclusion.getTheme());
                //类型 会议
                inclusionExamine.setType("3");
                inclusionExamine.setProjectId(uuid);
                inclusionExamine.setUserId(currentUser.getUserId().toString());
                inclusionExamine.setCreateBy(currentUser.getUserId().toString());
                inclusionExamine.setCreateTime(DateUtils.getNowDate());
                inclusionExamineMapper.insertInclusionExamine(inclusionExamine);


            }

        }


        return meetingInclusion.getMainId();
    }

    /**
     * 修改会议收录
     *
     * @param meetingInclusion 会议收录
     * @return 结果
     */
    @Override
    public int updateMeetingInclusion(MeetingInclusion meetingInclusion) {
        meetingInclusion.setUpdateTime(DateUtils.getNowDate());
        return meetingInclusionMapper.updateMeetingInclusion(meetingInclusion);
    }

    /**
     * 批量删除会议收录
     *
     * @param ids 需要删除的会议收录主键
     * @return 结果
     */
    @Override
    public int deleteMeetingInclusionByIds(String[] ids) {
        return meetingInclusionMapper.deleteMeetingInclusionByIds(ids);
    }

    /**
     * 删除会议收录信息
     *
     * @param id 会议收录主键
     * @return 结果
     */
    @Override
    public int deleteMeetingInclusionById(String id) {
        return meetingInclusionMapper.deleteMeetingInclusionById(id);
    }
}
